package com.abhimanyu.messaging;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.abhimanyu.messaging.model.IMessage;
import com.abhimanyu.messaging.model.TextMessage;

public class TextBeltMessageSender implements IMessageSender {

	private static final String NUMBER = "number";
	private static final String MESSAGE = "message";
	private static final String NUMBER_PREFIX = "+1";

	@SuppressWarnings("unchecked")
	public void sendMessage(IMessage message) {
		TextMessage textMessage = (TextMessage) message;
		JSONObject jsonMessage = new JSONObject();
		JSONArray jsonMessageArray = new JSONArray();
		String phoneNumber = textMessage.getPhoneNumber();
		jsonMessageArray.add(removePrefix(phoneNumber));
		jsonMessage.put(NUMBER, jsonMessageArray);
		jsonMessage.put(MESSAGE, textMessage.getMessageText());
		try {
			sendPost(jsonMessage);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String removePrefix(String phoneNumber) {
		if (phoneNumber.startsWith(NUMBER_PREFIX)) {
			return phoneNumber.substring(phoneNumber.indexOf(NUMBER_PREFIX)
					+ NUMBER_PREFIX.length());
		} else {
			return phoneNumber;
		}
	}

	// HTTP POST request
	private void sendPost(JSONObject message) throws Exception {

		String url = "http://textbelt.com/text";
		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();

		// add request header
		con.setRequestMethod("POST");
		con.setReadTimeout(0);
		con.setRequestProperty("Content-Type", "application/json");
		String urlParameters = message.toJSONString();

		// Send post request
		con.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
		wr.writeBytes(urlParameters);
		// wr.writeBytes(message.toJSONString());
		wr.flush();
		wr.close();

		int responseCode = con.getResponseCode();
		System.out.println("\nSending 'POST' request to URL : " + url);
		System.out.println("\nData : " + message.toJSONString());
		// System.out.println("Post parameters : " + urlParameters);
		System.out.println("Response Code : " + responseCode);

		BufferedReader in = new BufferedReader(new InputStreamReader(
				con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();

		// print result
		System.out.println(response.toString());

	}
}
